package com.music.peacerhythms.active;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.music.peacerhythms.R;
import com.music.peacerhythms.Uakj.MusicDataBase;
import com.music.peacerhythms.Uakj.MusicOperation;
import com.music.peacerhythms.Uakj.MyEvent;
import com.music.peacerhythms.Uakj.UaMeth;
import com.music.peacerhythms.databinding.ActivityAddconfigBinding;
import com.music.peacerhythms.databinding.ActivityEditconfigBinding;
import com.music.peacerhythms.info.MusicInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


public class EditConfigActivity extends AppCompatActivity implements View.OnClickListener {
    ActivityEditconfigBinding binding;
    List<MusicInfo> musicInfos;
    MusicAdapter adapter;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityEditconfigBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initMusic();
        initAdapter();
    }

    private MusicOperation musicOperation;
    private int poi;

    private void initMusic() {
        musicOperation = (MusicOperation) MusicDataBase.getInstance(this).musicOperation();
        musicInfos = musicOperation.initAllMusic();
        ArrayList<MusicInfo> musicInfoconfig = (ArrayList<MusicInfo>) getIntent().getExtras().getSerializable("music");
        binding.name.setText(musicInfoconfig.get(0).configname);
        poi = getIntent().getIntExtra("poi", -1);
        for (int i = 0; i < musicInfoconfig.size(); i++) {
            if (musicInfoconfig.get(i).isSelect) {
                musicInfos.get(i).isSelect = true;
                musicInfos.get(i).volume = musicInfoconfig.get(i).volume;
            }
        }

        binding.seekbar.setProgress(musicInfoconfig.get(0).Brightness);
        binding.tvseek.setText(musicInfoconfig.get(0).Brightness + "%");
    }

    private void initAdapter() {

        adapter = new MusicAdapter(this);
        binding.gridview.setAdapter(adapter);
        int screenBrightness = UaMeth.getScreenBrightness(this);


        binding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                binding.tvseek.setText(progress + "%");
                UaMeth.setAppScreenBrightness(progress*255/100, EditConfigActivity.this);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        iniOnclick();
    }


    private void iniOnclick() {

        binding.no.setOnClickListener(this);
        binding.confirm.setOnClickListener(this);
    }


    List<MusicInfo> checkmusicInfos;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {

            case R.id.no:
                finish();
                break;
            case R.id.confirm:

                checkmusicInfos = new ArrayList<>();
                //   List<MusicInfo> musicInfos = musicOperation.initAllMusic();
                for (MusicInfo musicInfo : musicInfos
                ) {
                    if (musicInfo.isSelect) {
                        checkmusicInfos.add(musicInfo);
                    }
                }
                if (checkmusicInfos.size() == 0) {
                    Toast.makeText(EditConfigActivity.this, "Please select a music", Toast.LENGTH_SHORT).show();
                    return;
                }

                for (MusicInfo musicInfo : musicInfos
                ) {
                    musicInfo.Brightness = binding.seekbar.getProgress();
                    musicInfo.configname = binding.name.getText().toString();
                }
                UaMeth.cgConfig(this, (ArrayList<MusicInfo>) musicInfos, poi);
                finish();
                break;
        }
    }


    public class MusicAdapter extends BaseAdapter {

        private Context mContext;

        public MusicAdapter(Context context) {
            this.mContext = context;
        }


        @Override
        public int getCount() {
            return musicInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MusicAdapter.ViewHolder viewHolder = null;


            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_grid_item, parent, false);
                viewHolder = new MusicAdapter.ViewHolder();
                viewHolder.itemImg = (ImageView) convertView.findViewById(R.id.iv_head);
                viewHolder.download = (ImageView) convertView.findViewById(R.id.download);
                viewHolder.name = (TextView) convertView.findViewById(R.id.music_name);
                viewHolder.seekBar = (SeekBar) convertView.findViewById(R.id.music_seekbar);
                viewHolder.llmusic = (LinearLayout) convertView.findViewById(R.id.ll_music);

                convertView.setTag(viewHolder);

            } else {
                viewHolder = (MusicAdapter.ViewHolder) convertView.getTag();
            }
            viewHolder.itemImg.setImageResource(musicInfos.get(position).imgId);
            viewHolder.name.setText(musicInfos.get(position).musicname);
            if (musicInfos.get(position).israw || musicInfos.get(position).isDownload) {
                viewHolder.download.setVisibility(View.GONE);
            } else {
                viewHolder.download.setVisibility(View.VISIBLE);
            }
            if (musicInfos.get(position).isSelect)
                viewHolder.itemImg.setBackgroundResource(R.drawable.bg_choose_circle);
            else
                viewHolder.itemImg.setBackgroundResource(R.drawable.bg_gray_circle);

            viewHolder.seekBar.setProgress(new Float(musicInfos.get(position).volume*100+"").intValue());
            viewHolder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                    if (progress != 100)
                        musicInfos.get(position).volume = Float.valueOf("0." + progress / 10);
                    else musicInfos.get(position).volume = 1f;
                    Log.e("aaaa", musicInfos.get(position).volume + "f");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });

            MusicAdapter.ViewHolder finalViewHolder = viewHolder;
            viewHolder.llmusic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (musicInfos.get(position).israw) {
                        if (musicInfos.get(position).isSelect)
                            finalViewHolder.itemImg.setBackgroundResource(R.drawable.bg_gray_circle);
                        else
                            finalViewHolder.itemImg.setBackgroundResource(R.drawable.bg_choose_circle);
                        musicInfos.get(position).isSelect = !musicInfos.get(position).isSelect;
                    } else {
                        if (musicInfos.get(position).isDownload) {
                            if (musicInfos.get(position).isSelect)
                                finalViewHolder.itemImg.setBackgroundResource(R.drawable.bg_gray_circle);
                            else
                                finalViewHolder.itemImg.setBackgroundResource(R.drawable.bg_choose_circle);
                            musicInfos.get(position).isSelect = !musicInfos.get(position).isSelect;
                        } else {
                            goDownload(musicInfos.get(position), position);
                        }
                    }
                }


            });


            return convertView;
        }


        class ViewHolder {
            ImageView itemImg;
            ImageView download;
            SeekBar seekBar;
            TextView name;
            LinearLayout llmusic;
        }
    }

    private void goDownload(MusicInfo musicInfo, int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String urlString = musicInfo.filepath;
                    File file = new File(getFilesDir().getAbsolutePath() + "/Download/");

                    if (!file.exists()) {
                        file.mkdirs();

                    }
                    String[] split = urlString.split("/");
                    file = new File(getFilesDir().getAbsolutePath() + "/Download/" + split[split.length - 1]);


                    if (!file.exists()) {
                        file.createNewFile();
                    }


                    OutputStream output = new FileOutputStream(file.getAbsolutePath());
                    URL url = new URL(urlString);
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    fileLength = connection.getContentLength();
                    InputStream in = new BufferedInputStream(connection.getInputStream());
                    byte[] arr = readStream(in);

                    output.write(arr, 0, fileLength);
                    output.flush();
                    output.close();
                    Log.e("aaaa", "success");
                    musicInfo.filepath = getFilesDir().getAbsolutePath() + "/Download/" + split[split.length - 1];
                    musicInfo.isDownload = true;
                    musicInfos.set(position, musicInfo);
                    musicOperation.updateData(musicInfo);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(EditConfigActivity.this, "Download failed, try again later", Toast.LENGTH_SHORT).show();

                    Log.e("aaaa", e.toString());
                }
            }
        }).start();

    }


    private int fileLength;


    public byte[] readStream(InputStream in) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = in.read(data)) != -1) {
            total += count;
            bos.write(data, 0, count);
        }
        bos.close();
        in.close();
        return bos.toByteArray();
    }
}


